<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="设备名称" prop="deviceName">
              <el-input v-model="queryParams.deviceName" placeholder="请输入设备名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="运行状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择运行状态" size="large" @change="handleQuery" style="width: 240px">
                <el-option :key="0" label="未连接" :value="0" />
                <el-option :key="1" label="运行中" :value="1" />
                <el-option :key="2" label="停止" :value="2" />
                <el-option :key="3" label="故障" :value="3" />
              </el-select>
            </el-form-item>
            <el-form-item label="安装位置" prop="installLocation">
              <el-input v-model="queryParams.installLocation" placeholder="请输入安装位置" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="所属区域" prop="area">
              <el-input v-model="queryParams.area" placeholder="请输入所属区域" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:deviceInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:deviceInfo:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:deviceInfo:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:deviceInfo:export']">导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              v-model:file-list="fileList"
              action=""
              class="upload-demo"
              accept=".xls,.xlsx"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :show-file-list="false"
              :http-request="uploadFileFn as UploadRequestHandler"
              :limit="1"
            >
              <el-button type="warning" :loading="uploadloading" plain icon="Upload" loading-icon="Loading" v-hasPermi="['system:deviceInfo:import']"
                >导入</el-button
              >
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              color="#5F6EE1"
              plain
              icon="TurnOff"
              @click="handleStratAndStop()"
              v-hasPermi="['system:deviceInfo:startandstop']"
              >一键启停</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="deviceInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备ID" align="center" prop="id" v-if="true" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备型号" align="center" prop="deviceModel">
          <template #default="scope">
            <!-- {{ getdeviceModel(scope.row.deviceModel) }} -->
            {{ scope.row.deviceModel }}
          </template>
        </el-table-column>
        <el-table-column label="厂商" align="center" prop="manufacturer" />
        <el-table-column label="安装位置" align="center" prop="installLocation" />
        <el-table-column label="所属区域" align="center" prop="area" />
        <el-table-column label="负责人" align="center" prop="principal" />
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template #default="scope">
            {{ getdsdevice(scope.row.deviceType) }}
          </template>
        </el-table-column>
        <el-table-column label="关联传感器/控制器ID" align="center" prop="relatedSensorControllerId" />
        <el-table-column label="当前状态" align="center" prop="status">
          <template #default="scope">
            <div>
              <span class="doll" :class="handleStatus(scope.row).color"></span><span>{{ handleStatus(scope.row).label || '--' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="启停" align="center" prop="status" v-hasPermi="['system:deviceInfo:startandstop']">
          <template #default="scope">
            <el-switch
              v-model.lazy="scope.row.status"
              :disabled="scope.row.status == 0 || scope.row.status == 3"
              :active-value="2"
              :inactive-value="1"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              active-text="启动"
              inactive-text="停止"
              :before-change="beforeChange"
              @click="singleChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:deviceInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:deviceInfo:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top">
              <el-button link type="primary" icon="View" @click="handleDetail(scope.row)" v-hasPermi="['system:deviceInfo:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="30%" append-to-body>
      <el-form ref="deviceInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备型号" prop="deviceModel">
          <el-input v-model="form.deviceModel" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="厂商" prop="manufacturer">
          <el-input v-model="form.manufacturer" placeholder="请输入厂商" />
        </el-form-item>
        <el-form-item label="安装位置" prop="installLocation">
          <el-input v-model="form.installLocation" placeholder="请输入安装位置" />
        </el-form-item>
        <el-form-item label="所属区域" prop="area">
          <el-input v-model="form.area" placeholder="请输入所属区域" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="form.principal" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="关联传感器ID" prop="relatedSensorControllerId">
          <el-input v-model="form.relatedSensorControllerId" placeholder="请输入关联传感器/控制器ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="一键启停" v-model="startandstopvisible" width="50%" append-to-body>
      <div>
        <el-switch
          v-model="startandstopqueryParams.status"
          :active-value="1"
          :inactive-value="2"
          class="mb-2"
          active-text="启动"
          inactive-text="停止"
          @change="getstartlist"
        />
      </div>
      <el-table :data="devicestartandstopInfoList" v-loading="sloading" @selection-change="handleSelectiontartandstopChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="设备型号" align="center" prop="deviceModel" />
        <el-table-column label="安装位置" align="center" prop="installLocation" />
        <el-table-column label="所属区域" align="center" prop="area" />
        <el-table-column label="设备类型" align="center" prop="deviceType">
          <template #default="scope">
            <div>pc</div>
          </template>
        </el-table-column>
        <el-table-column label="运行状态" align="center" prop="status">
          <template #default="scope">
            <div>
              <span class="doll" :class="handleStatus(scope.row).color"></span><span>{{ handleStatus(scope.row).label || '--' }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="startandstoptotal > 0"
        :total="startandstoptotal"
        v-model:page="startandstopqueryParams.pageNum"
        v-model:limit="startandstopqueryParams.pageSize"
        @pagination="getstartlist"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" :disabled="!ids.length" @click="submitForms">确 定</el-button>
          <el-button @click="cancels">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceInfo" lang="ts">
import {
  listDeviceInfo,
  getDeviceInfo,
  delDeviceInfo,
  addDeviceInfo,
  updateDeviceInfo,
  deviceInfoStart,
  deviceInfoStop,
  importDeviceInfo
} from '@/api/device/configuration/index';
import { getDicts } from '@/api/system/dict/data';
import { DeviceInfoVO, DeviceInfoQuery, DeviceInfoForm } from '@/api/device/configuration/types';
import type { UploadProps, UploadRequestHandler } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const deviceInfoList = ref<DeviceInfoVO[]>([]);

const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const uploadloading = ref(false);
const fileList = ref([]);

const startandstopvisible = ref(false);

const queryFormRef = ref<ElFormInstance>();
const deviceInfoFormRef = ref<ElFormInstance>();

const dsDeviceType = ref([]);
const dsDeviceModelType = ref([]);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceInfoForm = {
  id: undefined,
  deviceName: undefined,
  deviceModel: undefined,
  manufacturer: undefined,
  installLocation: undefined,
  area: undefined,
  principal: undefined,
  deviceType: undefined,
  relatedSensorControllerId: undefined,
  status: undefined,
  params: undefined
};
const data = reactive<PageData<DeviceInfoForm, DeviceInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deviceName: undefined,
    installLocation: undefined,
    area: undefined,
    deviceType: undefined,
    status: undefined
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }]
  }
});

const devicestartandstopInfoList = ref<DeviceInfoVO[]>([]);
const startandstopqueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  status: 1
});
const startandstoptotal = ref(0);
const sloading = ref(false);

const singleDevice = ref();

const { queryParams, form, rules } = toRefs(data);

/** 查询设备信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDeviceInfo(queryParams.value);
  deviceInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const getdeviceModel = (ds) => {
  return dsDeviceModelType.value.find((e) => e.dictValue == ds)?.dictLabel;
};

const getdsdevice = (ds) => {
  return dsDeviceType.value.find((e) => e.dictValue == ds)?.dictLabel;
};

/** 查询字典类型详细 */
const getBsDeviceTypes = async () => {
  const { data } = await getDicts('bs_device_type');
  dsDeviceType.value = data;
};

/** 查询字典类型详细 */
const getBsDeviceModelTypes = async () => {
  const { data } = await getDicts('bs_device_model');
  dsDeviceModelType.value = data;
};

/** 导出按钮操作 */
const handleStatus = (row?: DeviceInfoVO) => {
  switch (row.status) {
    case 1:
      return { color: 'start', label: '运行中' };
    case 2:
      return { color: 'stop', label: '停止' };
    case 3:
      return { color: 'malfunction', label: '故障' };
    case 0:
      return { color: 'unconnect', label: '未连接' };
    default:
      break;
  }
};

const singleChange = (row) => {
  singleDevice.value = row;
};

const beforeChange = (): Promise<boolean> => {
  return new Promise((_, reject) => {
    setTimeout(async () => {
      const { status, id } = singleDevice.value;
      let res;
      if (status == 1) {
        res = await deviceInfoStop({ devIds: [id] });
        proxy?.$modal.msgSuccess(`正在停止编号为${id}的设备`);
      }
      if (status == 2) {
        res = await deviceInfoStart({ devIds: [id] }).then((res) => {
          proxy?.$modal.msgSuccess(`正在启动编号为${id}的设备`);
        });
      }
      singleDevice.value = null;
      if (!res?.data) {
        return _(true);
      }
      return reject(false);
    }, 300);
  });
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加设备信息';
};

const handlePreview: UploadProps['onPreview'] = (file) => {
  console.log(file);
};

const handleRemove: UploadProps['onRemove'] = (file) => {
  console.log(file);
};

/* 导入按钮操作 */

const uploadFileFn = (data: any) => {
  uploadloading.value = true;
  const formData = new FormData();
  formData.append('file', data.file);
  importDeviceInfo(formData)
    .then((res) => {
      uploadloading.value = false;
      getList();
    })
    .catch((err) => {
      console.log(err);
    });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceInfoVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceInfo(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备信息';
};

const handleDetail = async (row?: DeviceInfoVO) => {
  router.push({ path: '/device/deviceDeatil', query: { id: row?.id } });
};

const getstartlist = async () => {
  ids.value = [];
  sloading.value = true;
  const data = { ...toRaw(startandstopqueryParams.value) };
  data.status = data.status == 1 ? 2 : 1;
  const res = await listDeviceInfo(data);
  devicestartandstopInfoList.value = res.rows;
  startandstoptotal.value = res.total;
  sloading.value = false;
};

const handleStratAndStop = async () => {
  await getstartlist();
  startandstopvisible.value = true;
};

const handleSelectiontartandstopChange = (selection: DeviceInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
};

const submitForms = async () => {
  const { status } = startandstopqueryParams.value;

  if (status === 1) {
    await deviceInfoStart({ devIds: ids.value }).then((res) => {
      proxy?.$modal.msgSuccess(`正在启动编号为${ids.value}的设备`);
    });
  }
  if (status === 2) {
    await deviceInfoStop({ devIds: ids.value }).then((res) => {
      proxy?.$modal.msgSuccess(`正在停止编号为${ids.value}的设备`);
    });
  }
  await getstartlist();
};

const cancels = () => {
  ids.value = [];
  startandstopvisible.value = false;
};

/** 提交按钮 */
const submitForm = () => {
  deviceInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDeviceInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/deviceInfo/export',
    {
      ...queryParams.value
    },
    `deviceInfo_${new Date().getTime()}.xlsx`
  );
};

onMounted(async () => {
  await getBsDeviceTypes();
  await getBsDeviceModelTypes();
  await getList();
});
</script>

<style lang="scss" scoped>
.doll {
  display: inline-block;
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 6px;
}

.stop {
  background-color: #ff922e;
}

.start {
  background-color: #4ec569;
}

.malfunction {
  background-color: #ee5715;
}

.unconnect {
  background-color: #6d6d6d;
}
</style>
